import { C20AllListing, Layout, UserSubPageBase } from "@/components";
import { useAuth } from "@/store/authContext";
import React, { useEffect, useState } from "react";
import {
  useUserInfo,
  getUserFav,
  addRemoveUserFav,
} from "@/store/userDataContext";
import { apiItemTypeMapping } from "@/utils/apiMapping";
import { View } from "@tarojs/components";
import style from "./index.module.scss";
import { useDidShow } from "@tarojs/taro";

export default function UserLikedItems() {
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { userData } = userInfoState;
  const { dispatchAuthAction } = useAuth();
  const [items, setItems] = useState<Array<any>>([]);

  useDidShow(() => {
    getUserFav(dispatchUserDataAction, userData!, {
      query: { limit: process.env.defaultPageSize!, page: 1 },
      authDispatch: dispatchAuthAction,
    });
  });

  useEffect(() => {
    if (userData!.likedItems) {
      setItems(userData!.likedItems!);
    }
  }, [userData?.likedItems]);

  const removeUserFav = async (id, type, i) => {
    const removed =
      (await addRemoveUserFav({
        query: { mainId: id, type: type },
        authDispatch: dispatchAuthAction,
      })) === false
        ? true
        : false;
    if (removed) {
      const newItems = items.filter((ni: any, index: number) => {
        return index !== i;
      });
      setItems(newItems);
    } else {
      return;
    }
  };

  return (
    <Layout>
      {items && (
        <UserSubPageBase
          title="我的收藏"
          subTitleDark={`您有${items.length}项收藏`}
          scrollable
        >
          <View className={style.list}>
            <C20AllListing
              cardType="vertical-list-card-center"
              cardList={items.map((likedItemData: any) => ({
                ...likedItemData,
                grayedOut: !likedItemData.available,
                id: likedItemData.id || likedItemData.productId,
                link: `pages/${
                  apiItemTypeMapping[likedItemData.mainType!]
                }-detail/index?id=${
                  likedItemData.id || likedItemData.productId
                }`,
              }))}
              removeCallback={removeUserFav}
            />
          </View>
        </UserSubPageBase>
      )}
    </Layout>
  );
}
